package com.demo.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.commons.lang3.StringUtils;

/**
 * 备份数据
 * 	将数据备份到文件中
 * 	从文件中将数据读取出来
 * @author ASUS
 *
 */
public interface FileBackup {
	/**
	 * 将数据备份到文件中
	 * @param path	文件路径
	 * @param object	数据
	 * @throws Exception 
	 */
	static void store(String path,Object object) throws Exception {
		if(StringUtils.isBlank(path)) {
			return;
		}
		
		File file = new File(path);
		
		if(!file.exists()) {
			file.createNewFile();
		}
		
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
		oos.writeObject(object);
		oos.flush();
		
		oos.close();
		
	}
	/**
	 * 从文件中读取
	 * @param path
	 * @return
	 * @throws Exception 
	 * @throws FileNotFoundException 
	 */
	static Object recover(String path,boolean isDelete) throws FileNotFoundException, Exception {
		//判空处理
		if(StringUtils.isBlank(path)) {
			return null;
		}
		//构建文件
		File file = new File(path);
		
		//如果文件不存在，意味数据为空
		if(!file.exists()) {
			return null;
		}
		
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
		Object object = ois.readObject();
		ois.close();
		
		if(isDelete)
			file.delete();
		return object;
	}
}
